<template>
  <div style='padding-top: 20px'>
    <j-form-container :disabled='disabled'>
      <a-form-model :model='form'
                    :rules='rules'
                    ref='formModel'
                    v-bind='layout'>
        <a-row>
          <a-col :span='24'>
            <a-form-model-item v-if='false' label='内容类型' prop='contentType'
                               style='margin-left: -100px;margin-bottom: 50px'>
              <a-radio-group v-model='form.contentType'>
                <!--          <a-radio :value="1">文章</a-radio>-->
                <!--          <a-radio :value="2">视频</a-radio>-->
                <!--          <a-radio :value="3">音频</a-radio>-->
                <!--          <a-radio :value="4">H5</a-radio>-->
                <a-radio v-for='item in contentTypes' :value='item.key' :key='item.key'>{{ item.name }}</a-radio>
              </a-radio-group>
            </a-form-model-item>

          </a-col>
          <a-form-model-item v-if='form.contentType === 1' label='内容主图' prop='mbLogoUrl'
                             style='margin-left: -100px;margin-bottom: 50px'>
            <image-choose v-model='form.mbLogoUrl' style='width: 250px'>内容主图从素材库中选择</image-choose>
            <span @click='copperUpload' style='cursor: pointer'>裁剪图片</span>

          </a-form-model-item>
          <a-form-model-item label='内容标题' prop='contentTitle' class='form_custom_class'
                             style='margin-left: -100px;'>
            <div style='display: flex;flex-direction: row;align-items: center'>
              <a-input v-model='form.contentTitle' placeholder='请输入内容标题'
                       style='font-size: 24px;line-height: 28px;height: 36px;flex: 1;margin-right: 5px'></a-input>
              <a-popover title='历史记录' trigger='click' @click='getTitleChangeHistory'>
                <template #content>
                  <a-table :columns='columns' :dataSource='titleChangeHistory'>
                    <template slot="operation" slot-scope="text, record">
                      <a-button @click="handleOperation(record)">恢复</a-button>
                    </template>
                  </a-table>
                </template>
                <a-button type='primary'>历史记录</a-button>
              </a-popover>
            </div>
          </a-form-model-item>
          <a-form-model-item label='输入摘要' style='margin-left: -100px;'>
            <a-input type='textarea' v-model='form.contentIntroduce' placeholder='请输入摘要'></a-input>
          </a-form-model-item>
        </a-row>
      </a-form-model>
      <a-modal :visible='cropperVisible' title='裁剪图片' :maskClosable='false' :confirmLoading='confirmLoading'
               :width='685'
               @cancel='cropperVisible = false'>
        <div style='display: flex;flex-direction: row;align-items: center;padding-bottom: 12px'>
          <span style='font-size: 16px;margin-right: 18px;color: #111111'>裁剪比例选择(宽*高)：</span>
          <a-radio-group v-model='cropperDefault' @change='cropperDefaultChange'>
            <a-radio :value='0'>320*240</a-radio>
<!--            <a-radio :value='1'>240*320</a-radio>-->
          </a-radio-group>
        </div>

        <a-row>
          <a-col :xs='24' :md='24' :style="{height: '640px',width:'640px'}">
            <vue-cropper ref='cropper' :img='options.img' :info='true'
                         :autoCrop='options.autoCrop'
                         :autoCropWidth='options.autoCropWidth'
                         :autoCropHeight='options.autoCropHeight'
                         :fixedBox='options.fixedBox'
                         :fixed='options.fixed'
                         :fixedNumber='options.fixedNumber'
                         @realTime='realTime'>
            </vue-cropper>
          </a-col>
        </a-row>
        <template slot='footer'>
          <a-button key='back' @click='cancelHandel'>取消</a-button>
          <a-button key='submit' type='primary' :loading='confirmLoading' @click='okHandel'>确定</a-button>
        </template>
      </a-modal>

    </j-form-container>
  </div>
</template>

<script>
//内容表单
import BorderBox from '../BorderBox'
import { getAction } from '@/api/manage'
import { ajaxGetDictItems } from '@/api/api'
import ImageChoose from '../ImageChoose'
import { contentTypes } from '@/utils/xinkeUtil'
import {
  axios
} from '@/utils/request'
import {
  VueCropper
} from 'vue-cropper'

export default {
  name: 'ContentForm',
  components: { ImageChoose, BorderBox, VueCropper },
  props: ['params', 'disabled'],
  data() {
    return {
      contentTypes: contentTypes,
      rules: {
        contentType: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ],
        // mbLogoUrl: [
        //   {required: true, message: '请选择内容主图', trigger: 'blur|change'},
        // ],
        contentTitle: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ]
      },
      form: {
        contentType: 1,
        isWatermark: 0
      },
      layout: {
        labelCol: { md: 7, lg: 6 },
        wrapperCol: { md: 17, lg: 18 }
      },
      categoryList: [],
      themeList: [],
      options: {
        img: '',
        autoCrop: true,
        autoCropWidth: 320,
        autoCropHeight: 240,
        fixedBox: false,
        fixed: true,
        fixedNumber: [4, 3]
      },
      cropperVisible: false,
      cropperDefault: 0,
      confirmLoading: false,
      previews: {},
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      titleChangeHistory: [],
      columns: [
        {
          title: '标题',
          dataIndex: 'title',
          key: 'title'
        },
        {
          title: '修改人',
          dataIndex: 'createBy',
          key: 'createBy'
        },
        {
          title: '修改时间',
          dataIndex: 'createTime',
          key: 'createTime'
        },
        {
          title: '操作',
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  watch: {
    'form.contentType': {
      immediate: true,
      handler: function(newVal) {
        this.$emit('contentTypeChange', newVal)
      }
    }
  },
  created() {
    this.loadCategory()
    this.loadTheme()
    this.queryInfo()
  },
  mounted() {
  },
  methods: {
    handleOperation(record) {
      console.log(record);
      if(record !=null && record != ''){
         this.form.contentTitle = record.title
      }
    },
    //裁剪
    copperUpload() {
      let that = this

      // console.log(file)
      // this.options.img = 'https://huishi-media.oss-cn-hangzhou.aliyuncs.com/temp/课程对比分析_1680593761748.png';
      console.log(this.form.mbLogoUrl)
      getAction('big/data/imageUrlToBase64?url=' + this.form.mbLogoUrl).then(res => {
        if (res.success) {
          that.options.img = res.result
          that.cropperVisible = true
        }
      })

      // this.resolve = resolve;
    },
    realTime(data) {
      console.log(data)
      this.previews = data
    },
    cancelHandel() {
      this.cropperVisible = false
      // this.resolve();

    },

    okHandel() {
      this.cropperVisible = false
      this.$refs.cropper.getCropData((data) => {
        let file = this.dataURLToFile(data, '默认')
        console.log(file)
        this.updateImg(file)
      })
    },
    updateImg(file) {
      let formData = new FormData()
      let fileOfBlob = new File([file], '.jpg') // 命名图片名
      formData.append('file', fileOfBlob)
      axios({
        url: this.uploadAction,
        method: 'post',
        headers: {
          'Content-Type': 'multipart/form-data;charset=UTF-8'
        },
        data: formData
      }).then(res => {
        if (res.success && res.code === 0) {
          this.form.mbLogoUrl = res.message
          this.$message.success('修改成功')
          this.materialNameModal = false

          if (this.cropperVisible) {
            this.cropperVisible = false
          }
        }
      })
    },
    dataURLToFile(dataURL, filename) {

      const arr = dataURL.split(','),
        mime = arr[0].match(/:(.*?);/)[1], //mime类型 image/png
        bstr = atob(arr[1]) //base64 解码

      let n = bstr.length,
        u8arr = new Uint8Array(n)

      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }

      return new File([u8arr], filename, { type: mime })
      //return new Blob([a8arr], {type: mime});
    },
    // 分类
    loadCategory() {
      ajaxGetDictItems('content_category').then(res => {
        if (res.success) {
          this.categoryList = res.result
        }
      })
    },
    //主题
    loadTheme() {
      getAction('them/thmThemeInfo/list').then(res => {
        if (res.success) {
          this.themeList = res.result.records
        }
      })
    },
    //回显信息
    queryInfo() {
      getAction('task/taskInfo/queryTaskContentInfo', this.params).then(res => {
        if (res.success) {
          const {
            contentType, mbLogoUrl, contentTitle, contentSubTitle, contentIntroduce,
            categoryId, categoryName, themeId, themeName, isWatermark, contentNo,
            videoUrl, voiceUrl, htmlUrl
          } = res.result
          const tempForm = {
            contentType: contentType || this.form.contentType,
            isWatermark: isWatermark || this.form.isWatermark,
            mbLogoUrl,
            contentTitle,
            contentSubTitle,
            contentIntroduce,
            contentNo,
            videoUrl,
            voiceUrl,
            htmlUrl
          }
          if (categoryId) {
            tempForm.category = { key: categoryId, label: categoryName }
          }
          if (themeId) {
            tempForm.theme = { key: themeId, label: themeName }
          }
          this.form = tempForm
        }
      })
    },
    selfValidate() {
      return new Promise((resolve, reject) => {
        this.$refs.formModel.validate(validate => {
          if (validate) {
            if (this.form.category) {
              this.form.categoryId = this.form.category.key
              this.form.categoryName = this.form.category.label
            }
            if (this.form.theme) {
              this.form.themeId = this.form.theme.key
              this.form.themeName = this.form.theme.label
            }
            resolve({ key: 'textContentInfo', value: this.form })
          } else {
            reject('请填写内容必要信息')
          }
        })
      })
    },
    getContentInfo() {
      return this.form
    },
    cropperDefaultChange(value) {
      this.options.fixedNumber = this.cropperDefault === 1 ? [3, 4] : [4, 3]
      this.$refs.cropper.reload()
    },
    getTitleChangeHistory() {
      let taskNo = this.$route.query.taskNo
      getAction('content/conTitleRecord/queryContentTitleRecord', { taskNo: taskNo }).then(res => {
        if (res.success) {
          this.titleChangeHistory = res.result
        }
      }).catch(e => {
        console.error(e)
      })
    }
  }
}
</script>
<style>
.form_custom_class {
  .ant-form-item-required {
    font-size: 24px !important;
  }
}
</style>
<style scoped>

</style>